<template>
	<view class="container">
		<!--  <view class="header">
      <text class="title">AI 助手</text>
    </view> -->

		<scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" :scroll-with-animation="true"
			@scrolltoupper="loadMoreMessages" ref="chatScroll">
			<view class="message-list">
				<view v-for="(message, index) in messages" :key="index" class="message-item"
					:class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }">
					<view class="message-avatar">
						<image :src="message.role === 'user' ? '/static/user-avatar.png' : '/static/ai-avatar.png'"
							mode="aspectFill"></image>
					</view>
					<view class="message-content">
						<text class="message-text" v-if="message.role === 'user'">{{ message.content }}</text>
						<text class="message-text" selectable="true" @longpress="copyText"
							v-else>{{ message.content }}</text>
					</view>
				</view>

				<!-- 流式输出的消息 -->
				<view v-if="isStreaming" class="message-item ai-message">
					<view class="message-avatar">
						<image src="/static/ai-avatar.png" mode="aspectFill"></image>
					</view>
					<view class="message-content">
						<text class="message-text">{{ streamingContent }}</text>
						<view v-if="streamingContent === ''" class="typing-indicator">
							<view class="dot"></view>
							<view class="dot"></view>
							<view class="dot"></view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<view class="input-area">
			<view class="input-box">
				<textarea v-model="inputMessage" class="input-field" placeholder="输入消息..." :disabled="isStreaming"
					auto-height :maxlength="-1" @confirm="sendMessage"></textarea>
				<view class="send-btn" @tap="sendMessage" :class="{ 'disabled': !inputMessage || isStreaming }">
					<text class="send-icon">发送</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const API_URL = 'https://api.deepseek.com/v1/chat/completions' // 替换为实际API地址
	const API_KEY = 'sk-11578c688b5c457abcb33e052f6c4f21' // 替换为你的API密钥
	export default {
		data() {
			return {
				messages: [],
				inputMessage: '',
				scrollTop: 0,
				isStreaming: false,
				streamingContent: '',
				streamInterval: null,
				currentIndex: 0,
				mockResponses: [
					"你好！我是AI助手，很高兴为你提供帮助。",
					"uni-app是一个使用Vue.js开发所有前端应用的框架，开发者编写一套代码，可发布到iOS、Android、Web（响应式）、以及各种小程序（微信/支付宝/百度/头条/飞书/QQ/快手/钉钉/淘宝）、快应用等多个平台。",
					"流式输出是一种实时显示内容的技术，它可以让用户看到内容逐步生成的过程，而不是等待整个内容加载完成后一次性显示。这种技术常用于聊天机器人、代码编辑器和实时数据可视化等场景。"
				],
				text: '你好 ， 我是周娟',
				rate: 1.0,
				pitch: 1.0,
				volume: 1.0,
				voices: [{
						id: 'default',
						name: '默认语音'
					},
					{
						id: 'female',
						name: '女声'
					},
					{
						id: 'male',
						name: '男声'
					}
				],
				selectedVoiceIndex: 0,
				isSpeaking: false,
				isPaused: false,
				speechInstance: null,
				innerAudioContext: null,
				utterThis: null
			};
		},
		onLoad() {
			// 添加一些初始消息
			this.messages = [{
					role: 'user',
					content: '你好！'
				},
				{
					role: 'assistant',
					content: '你好！我是AI助手，有什么可以帮助你的吗？'
				}
			];

			// 滚动到底部
			this.$nextTick(() => {
				this.scrollToBottom();
			});
			// this.speakText()
		},
		methods: {
			speakText() {
				this.utterThis = new SpeechSynthesisUtterance('');
				this.utterThis.pitch = 1; // 音高
				this.utterThis.rate = 1; // 语速
				this.utterThis.volume = 1; // 音量
				this.utterThis.lang = 'zh-CN';
				this.utterThis.text = "要播报的文本内容";
				window.speechSynthesis.speak(this.utterThis); // 开始朗读

				this.utterThis.onend = () => { // 结束事件
					window.speechSynthesis.cancel(); // 注销合成方法
				};
			},

			copyText() {
				uni.setClipboardData({
					data: this.streamingContent,
					success() {
						uni.showToast({
							title: '已复制到剪贴板',
							icon: 'none',
							position: 'top'
						})
					}
				})
			},
			scrollToBottom() {
				// 获取消息列表高度并滚动到底部
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.message-list').boundingClientRect(data => {
						if (data) {
							this.scrollTop = data.height * 2; // 乘以2确保滚动到底部
						}
					}).exec();
				});
			},

			loadMoreMessages() {
				// 加载更多消息的逻辑
				uni.showToast({
					title: '没有更多消息了',
					icon: 'none'
				});
			},

			sendMessage() {
				if (!this.inputMessage || this.isStreaming) return;

				const userMessage = this.inputMessage.trim();
				this.inputMessage = '';

				// 添加用户消息
				this.messages.push({
					role: 'user',
					content: userMessage
				});

				this.scrollToBottom();

				// 开始流式输出
				this.startStreaming();
			},

			async startStreaming() {
				this.isStreaming = true;
				this.streamingContent = '';
				const res = await uni.request({
					url: API_URL,
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'Authorization': `Bearer ${API_KEY}`
					},
					data: {
						model: 'deepseek-chat', // 模型
						messages: this.messages
					}
				})
				// 随机选择一个回复
				// const responseIndex = Math.floor(Math.random() * this.mockResponses.length);
				// const fullResponse = this.mockResponses[responseIndex];

				const fullResponse = res.data.choices[0].message.content;

				// const currentIndex = 0;
				var that = this
				// 模拟流式输出
				this.streamInterval = setInterval(() => {
					if (this.currentIndex < fullResponse.length) {
						// 添加下一个字符
						this.streamingContent += fullResponse[this.currentIndex];
						this.currentIndex++;
						this.scrollToBottom();
					} else {
						// 流式输出完成
						clearInterval(this.streamInterval);

						// 将流式内容添加到消息列表
						this.messages.push({
							role: 'assistant',
							content: this.streamingContent
						});

						// 重置流式状态
						this.isStreaming = false;
						// this.streamingContent = '';

						this.scrollToBottom();
					}
				}, 50); // 每50毫秒添加一个字符
			},

			// 模拟与真实API的流式输出
			async streamFromAPI(prompt) {
				this.isStreaming = true;
				this.streamingContent = '';

				try {
					// 这里是模拟API调用，实际使用时替换为真实API
					const mockAPIResponse = async (prompt) => {
						return new Promise((resolve) => {
							const responseIndex = Math.floor(Math.random() * this.mockResponses
								.length);
							resolve(this.mockResponses[responseIndex]);
						});
					};

					const fullResponse = await mockAPIResponse(prompt);

					// 模拟流式输出
					for (let i = 0; i < fullResponse.length; i++) {
						this.streamingContent += fullResponse[i];
						this.scrollToBottom();

						// 使用setTimeout模拟网络延迟
						await new Promise(resolve => setTimeout(resolve, 50));
					}

					// 流式输出完成
					this.messages.push({
						role: 'assistant',
						content: this.streamingContent
					});

				} catch (error) {
					console.error('流式输出错误:', error);
					uni.showToast({
						title: '获取回复失败',
						icon: 'none'
					});
				} finally {
					// 重置流式状态
					this.isStreaming = false;
					this.streamingContent = '';
					this.scrollToBottom();
				}
			}
		},
		beforeDestroy() {
			// 清除定时器
			if (this.streamInterval) {
				clearInterval(this.streamInterval);
			}
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.header {
		padding: 15px;
		background-color: #ffffff;
		border-bottom: 1px solid #eaeaea;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title {
		font-size: 18px;
		font-weight: bold;
	}

	.chat-container {
		flex: 1;
		padding: 10px 15px;
	}

	.message-list {
		display: flex;
		flex-direction: column;
	}

	.message-item {
		display: flex;
		margin-bottom: 15px;
		align-items: flex-start;
	}

	.user-message {
		flex-direction: row-reverse;
	}

	.message-avatar {
		width: 40px;
		height: 40px;
		border-radius: 20px;
		overflow: hidden;
		margin: 0 10px;
		flex-shrink: 0;
	}

	.message-avatar image {
		width: 100%;
		height: 100%;
	}

	.message-content {
		max-width: 70%;
		padding: 10px 15px;
		border-radius: 10px;
		background-color: #ffffff;
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
	}

	.user-message .message-content {
		background-color: #007AFF;
	}

	.user-message .message-text {
		color: #ffffff;
	}

	.ai-message .message-content {
		background-color: #ffffff;
	}

	.message-text {
		font-size: 16px;
		line-height: 1.5;
		word-break: break-word;
	}

	/* 打字指示器样式 */
	.typing-indicator {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 5px 0;
	}

	.dot {
		width: 8px;
		height: 8px;
		border-radius: 50%;
		background-color: #ccc;
		margin: 0 2px;
		animation: typing 1.5s infinite ease-in-out;
	}

	.dot:nth-child(1) {
		animation-delay: 0s;
	}

	.dot:nth-child(2) {
		animation-delay: 0.2s;
	}

	.dot:nth-child(3) {
		animation-delay: 0.4s;
	}

	@keyframes typing {

		0%,
		60%,
		100% {
			transform: translateY(0);
			opacity: 0.6;
		}

		30% {
			transform: translateY(-5px);
			opacity: 1;
		}
	}

	.input-area {
		padding: 10px 15px;
		background-color: #ffffff;
		border-top: 1px solid #eaeaea;
	}

	.input-box {
		display: flex;
		align-items: flex-end;
	}

	.input-field {
		flex: 1;
		padding: 10px 15px;
		border: 1px solid #ddd;
		border-radius: 20px;
		font-size: 16px;
		background-color: #f9f9f9;
		max-height: 120px;
		min-height: 40px;
	}

	.send-btn {
		width: 60px;
		height: 40px;
		border-radius: 20px;
		background-color: #007AFF;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 10px;
	}

	.send-btn.disabled {
		background-color: #ccc;
	}

	.send-icon {
		color: #ffffff;
		font-size: 14px;
	}
</style>